<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="模型设计">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" id="moss-basicTable" :bordered="false">
        <template #tableTitle>
          <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新增模型
          </n-button>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-drawer v-model:show="showDrawer" width="85%">
      <n-drawer-content :title="editTitle" :native-scrollbar="false">
        <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="8" label="模型名称" path="modelName">
              <n-input maxlength="64" show-count placeholder="请输入模型名称" v-model:value="fromValues.modelName" />
            </n-form-item-gi>
            <n-form-item-gi :span="8" label="模型说明" path="modelComment">
              <n-input maxlength="100" show-count placeholder="请输入模型说明" v-model:value="fromValues.modelComment" />
            </n-form-item-gi>
            <n-form-item-gi :span="8" label="数据源" path="dataSourceId">
              <n-select v-model:value="fromValues.dataSourceId" placeholder="请选择数据源" :options="dataSourceList" />
            </n-form-item-gi>
          </n-grid>
        </n-form>
        <n-alert title="提示" type="info">
          字段配置请按照表的设计规范，选择项表示该字段的下拉选择项，排序请根据实际需要进行调整。
        </n-alert>
        <div style="margin-top: 15px;"><n-button type="primary" @click="handleAddField">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加字段
          </n-button></div>
        <n-data-table style="margin-top: 15px;" :columns="fieldColumns" :data="fieldList" :bordered="false"
          :loading="pageLoading" :max-height="460" />

        <template #footer>
          <n-space>
            <n-button @click="handleCloseDrawer">
              取消
            </n-button>
            <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">
              确定
            </n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>

    <!-- SQL-MODEL -->
    <n-modal v-model:show="showSqlModal" :show-icon="false" preset="dialog" title="模型SQL脚本" style="width: 720px;">
      <div class="highlightjs-auto">
        <n-spin size="small" :show="spinShow">
          <highlightjs autodetect :code="sqlScript" />
        </n-spin>
      </div>
      <div style="justify-content: end;display: flex;margin-top: 15px;">
        <n-button type="primary" :loading="formBtnLoading" @click="handleCloseSqlModel">关闭</n-button>
      </div>
    </n-modal>

    <!-- 代码生成 -->
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="生成代码">
      <n-form :model="fromCodeValues" :rules="codeRules" ref="formCodeRef" label-placement="top" :label-width="120"
        class="py-4">
        <n-form-item label="包名" path="packageName">
          <n-input maxlength="100" show-count placeholder="请输入包名" v-model:value="fromCodeValues.packageName" />
        </n-form-item>
        <n-form-item label="服务简称" path="serviceAbbreviation">
          <n-input maxlength="32" show-count placeholder="请输入服务简称" v-model:value="fromCodeValues.serviceAbbreviation" />
        </n-form-item>
        <n-form-item label="所属服务" path="serviceName">
          <n-select v-model:value="fromCodeValues.serviceName" placeholder="请选择状态" :options="serverList" />
        </n-form-item>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmCodeForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted, unref } from 'vue';
import { useMessage, useDialog, NInput, NInputNumber, NCheckbox, NButton, NSelect, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import {
  modelDesignPage, removeModelDesign, saveModelDesign, updateModelDesign, defaultField, modeDetail,
  getSqlScript, syncDataSource, recallSync, generateCode
} from '@/api/plugins/modelDesign';
import { dataSourcePage } from '@/api/plugins/dataSource';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
import { columns } from './columns';
import { dictGroup } from '@/api/system/dict';
import 'highlight.js/styles/atom-one-dark.min.css';
import 'highlight.js/lib/common';
import hljsVuePlugin from "@highlightjs/vue-plugin";
const highlightjs = hljsVuePlugin.component;
const message = useMessage();
const formRef: any = ref(null);
const formCodeRef: any = ref(null);
const actionRef = ref();
const showDrawer = ref<boolean>(false);
const formBtnLoading = ref<boolean>(false);
const pageLoading = ref<boolean>(false);
const isAdd = ref<boolean>(true);
const showSqlModal = ref<boolean>(false);
const editTitle = ref<string>('');
const dataSourceList = ref<any[]>([]);
const dialog = useDialog();
const fieldList = ref<any[]>([]);
const dataType = ref<any[]>([]);
const sqlScript = ref<string>('');
const spinShow = ref<boolean>(false);
const showModal = ref<boolean>(false);
const serverList = ref<any[]>([]);
const currentModel = ref<any>({});
const syncStatusOps = [{ label: '已同步', value: 1 }, { label: '未同步', value: 2 }];
const defaultValueRef = () => ({
  id: null,
  /**模型名称*/
  modelName: '',
  /**模型注释*/
  modelComment: '',
  /**数据源ID*/
  dataSourceId: null,
  /**模型字段*/
  modelFieldFroms: [],
});
let fromValues = reactive(defaultValueRef());
const fieldColumns = [
  {
    title: '字段',
    key: 'field',
    render(row, index) {
      return h(NInput, {
        value: row.field,
        onUpdateValue(v) {
          fieldList.value[index].field = v
        }
      })
    }
  },
  {
    title: '数据类型',
    key: 'dataType',
    width: 140,
    render(row, index) {
      return h(NSelect, {
        value: row.dataType,
        filterable: true,
        options: dataType.value,
        onUpdateValue(v) {
          fieldList.value[index].dataType = v
        }
      })
    }
  },
  {
    title: '长度',
    key: 'maxLength',
    width: 130,
    render(row, index) {
      return h(NInputNumber, {
        value: row.maxLength,
        onUpdateValue(v) {
          fieldList.value[index].maxLength = v
        }
      })
    }
  },
  {
    title: '保留小数位',
    key: 'reserve',
    width: 130,
    render(row, index) {
      return h(NInputNumber, {
        value: row.reserve,
        onUpdateValue(v) {
          fieldList.value[index].reserve = v
        }
      })
    }
  },
  {
    title: '主键?',
    key: 'primaryKey',
    width: 60,
    render(row, index) {
      return h(NCheckbox, {
        checked: row.primaryKey,
        onChange(v) {
          fieldList.value[index].primaryKey = v
        }
      })
    }
  },
  {
    title: '非空?',
    key: 'nonEmpty',
    width: 60,
    render(row, index) {
      return h(NCheckbox, {
        checked: row.nonEmpty,
        onChange(v) {
          fieldList.value[index].nonEmpty = v
        }
      })
    }
  },
  {
    title: '排序',
    key: 'orderNum',
    width: 130,
    render(row, index) {
      return h(NInputNumber, {
        value: row.orderNum,
        onUpdateValue(v) {
          fieldList.value[index].orderNum = v
        }
      })
    }
  },
  {
    title: '默认字段?',
    key: 'isDefault',
    width: 90,
    render(row, index) {
      return h(NCheckbox, {
        checked: row.isDefault,
        onChange(v) {
          fieldList.value[index].isDefault = v
        }
      })
    }
  },
  {
    title: '表单参数?',
    key: 'isForm',
    width: 90,
    render(row, index) {
      return h(NCheckbox, {
        checked: row.isForm,
        onChange(v) {
          fieldList.value[index].isForm = v
        }
      })
    }
  },
  {
    title: '查询参数?',
    key: 'isQuery',
    width: 90,
    render(row, index) {
      return h(NCheckbox, {
        checked: row.isQuery,
        onChange(v) {
          fieldList.value[index].isQuery = v
        }
      })
    }
  },
  {
    title: '字段说明',
    key: 'fieldComment',
    render(row, index) {
      return h(NInput, {
        value: row.fieldComment,
        onUpdateValue(v) {
          fieldList.value[index].fieldComment = v
        }
      })
    }
  },
  {
    title: '选择项',
    key: 'fieldSelect',
    render(row, index) {
      return h(NInput, {
        value: row.fieldSelect,
        onUpdateValue(v) {
          fieldList.value[index].fieldSelect = v
        }
      })
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    render(row) {
      return row.isDefault ? '' : h(
        NButton,
        {
          size: 'small',
          type: 'error',
          onClick: () => handleDelField(row),
        },
        { default: () => '删除' }
      )
    }

  }
]

/**
 * 删除字段
 * @param row 
 */
const handleDelField = (row) => {
  fieldList.value = fieldList.value.filter(item => item.id !== row.id)
}
const rules: FormRules = {
  modelName: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入模型名称',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  modelComment: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入模型描述',
  },
  dataSourceId: {
    type: 'number',
    required: true,
    trigger: ['blur', 'select'],
    message: '请选择数据源',
  },
};
/**
 * 添加字段
 */
const handleAddField = () => {
  fieldList.value.push({
    id: fieldList.value.length + 1,
    field: '',
    dataType: '',
    maxLength: null,
    reserve: null,
    primaryKey: false,
    nonEmpty: false,
    orderNum: 1,
    isDefault: false,
    isForm: false,
    isQuery: false,
    fieldComment: '',
    fieldSelect: ''
  });
}
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'modelName',
    component: 'NInput',
    label: '模型名称',
    componentProps: {
      placeholder: '请输入模型名称',
    },
  },
  {
    field: 'syncStatus',
    component: 'NSelect',
    label: '同步状态',
    componentProps: {
      placeholder: '请选择同步状态',
      options: syncStatusOps,
    },
  },
];
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 120,
  schemas,
});
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
      dropDownActions: [
        {
          label: '获取SQL',
          key: 'GET_SQL',
          ifShow: () => {
            return true;
          },
          //auth: ['base_sys_user_reset_pwd'],
        },
        {
          label: '同步数据源',
          key: 'SYNC_DATA_SOURCE',
          ifShow: () => {
            return record.syncStatus === 2 ? true : false;
          },
          //auth: ['base_sys_user_lock_account'],
        },
        {
          label: '撤回同步',
          key: 'WITHDRAW',
          ifShow: () => {
            return record.syncStatus === 1 ? true : false;
          },
          //auth: ['base_sys_user_unlock_account'],
        },
        {
          label: '生成代码',
          key: 'USER_TRANSFER',
          ifShow: () => {
            return true;
          },
          //auth: ['base_sys_user_position_transfer'],
        }
      ],
      select: (key) => {
        if (key === 'GET_SQL') {
          handleGetSql(record);
        }
        if (key === 'SYNC_DATA_SOURCE') {
          syncDataSourceApi(record);
        }
        if (key === 'WITHDRAW') {
          recallSyncApi(record);
        }
        if (key === 'USER_TRANSFER') {
          handleOpenModel(record);
        }
      },
    });
  },
});
const defaultCodeValueRef = () => ({
  id: null,
  /*** 包名*/
  packageName: '',
  /*** 服务简称*/
  serviceAbbreviation: '',
  /*** 服务名称*/
  serviceName: ''
});
let fromCodeValues = reactive(defaultCodeValueRef());
const codeRules: FormRules = {
  packageName: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入包名',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  serviceAbbreviation: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入服务简称',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  serviceName: {
    type: 'string',
    required: true,
    trigger: ['blur', 'select'],
    message: '请选择所属服务',
  },
};
/**
 * 关闭生成代码弹框
 */
const handleCloseModel = () => {
  fromCodeValues = Object.assign(unref(fromCodeValues), defaultCodeValueRef());
  showModal.value = false;
}

/**
 * 打开生成代码弹框
 */
const handleOpenModel = (record) => {
  currentModel.value = record;
  showModal.value = true;
}

/**
 * 代码生成提交表单
 * @param e 
 */
const confirmCodeForm = (e: any) => {
  e.preventDefault();
  formCodeRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      fromCodeValues = Object.assign(fromCodeValues, { id: currentModel.value.id });
      const res = await generateCode(fromCodeValues);
      if (!res.data) {
        message.warning('文件下载失败');
        return;
      }
      formBtnLoading.value = false;
      handleCloseModel();
      const blob = new Blob([res.data]);
      const objectURL = URL.createObjectURL(blob);
      let btn = document.createElement('a');
      btn.download = decodeURIComponent(getFileNameFromHeaders(res.headers));
      btn.href = objectURL;
      btn.click();
      URL.revokeObjectURL(objectURL);
      btn = null;
    } else {
      message.error('请填写完整信息');
    }
  });
}

/**
 * 获取响应的文件名
 * @param headers 
 */
 const getFileNameFromHeaders = (headers) =>{
  const contentDisposition = headers['content-disposition'];
  const matches = contentDisposition.match(/filename=(?<fileName>.+)/);
  return matches && matches.groups.fileName;
}

/**
 * 获取SQL脚本
 * @param record 
 */
const handleGetSql = async (record) => {
  showSqlModal.value = true;
  spinShow.value = true;
  const data = await getSqlScript({ id: record.id });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.msg + '-' + resultMsg);
    spinShow.value = false;
  }
  if (data.code === ResultEnum.SUCCESS) {
    sqlScript.value = data.data;
    spinShow.value = false;
  }
}

const handleCloseSqlModel = () => {
  showSqlModal.value = false;
}

/**
 * 同步数据源
 * @param record 
 */
const syncDataSourceApi = async (record) => {
  const data = await syncDataSource({ id: record.id });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.msg + '-' + resultMsg);
    spinShow.value = false;
  }
  if (data.code === ResultEnum.SUCCESS) {
    reloadTable();
    message.success(data.msg);
  }
}

/**
 * 撤回同步
 * @param record 
 */
const recallSyncApi = async (record) => {
  const data = await recallSync({ id: record.id });
  if (data.code !== ResultEnum.SUCCESS) {
    const resultMsg = data.data ? data.data : '';
    message.error(data.msg + '-' + resultMsg);
    spinShow.value = false;
  }
  if (data.code === ResultEnum.SUCCESS) {
    reloadTable();
    message.success(data.msg);
  }
}

function createActions(record) {
  return [
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, false),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
const loadDataTable = async (res: any) => {
  return await modelDesignPage({ ...getFieldsValue(), ...res });
};

const onCheckedRow = (rowKeys: any[]) => {
  console.log(rowKeys);
}

const reloadTable = () => {
  actionRef.value.reload();
}
/**
 * 查询
 */
const handleSubmit = () => {
  reloadTable();
}
/**
 * 重置查询
 */
const handleReset = () => {
  reloadTable();
}

/**
 * 新增更新
 * @param record 
 * @param addStatus 
 */
const handleEdit = async (record: Recordable, addStatus: boolean) => {
  resetFrom();
  isAdd.value = addStatus;
  editTitle.value = addStatus ? '新增模型' : `编辑${record.modelName}`;
  showDrawer.value = true;
  pageLoading.value = true;
  if (addStatus) {
    const data = await defaultField({});
    fieldList.value = data;
  } else {
    const data = await modeDetail({ id: record.id });
    fromValues = Object.assign(fromValues, data);
    fieldList.value = data.modelFields;
  }
  pageLoading.value = false;
}

/**
 * 关闭抽屉
 */
const handleCloseDrawer = () => {
  showDrawer.value = false;
}

/**
 * 重置提交
 */
const resetFrom = () => {
  fromValues = Object.assign(unref(fromValues), defaultValueRef());
  fromValues.modelFieldFroms = [];
}

/**
 * 提交表单
 * @param e 
 */
const confirmForm = (e: any) => {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      fromValues = Object.assign(fromValues, { modelFieldFroms: fieldList.value });
      const data = isAdd.value ? await saveModelDesign(fromValues) : await updateModelDesign(fromValues);
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
        formBtnLoading.value = false;
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        showDrawer.value = false;
        formBtnLoading.value = false;
        resetFrom();
        reloadTable();
      }
    } else {
      message.error('请填写完整信息');
    }
  });
}
/**
 * 删除确认
 * @param record 
 */
const handleDelete = (record: Recordable) => {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.modelName}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await removeModelDesign({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        reloadTable();
      }
    },
  })
}

/**
 * 数据源下拉
 */
const loadDataSource = async () => {
  const data = await dataSourcePage({ current: 1, size: 30 });
  const arry = data.records.map(item => ({ label: item.databaseName, value: item.id }));
  dataSourceList.value = arry;
}
/**
 * 数据源类型
 */
const getDtaType = async () => {
  const data = await dictGroup({ dictGroup: 'data_type' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  dataType.value = arry;
}

/**
 * 服务列表
 */
const getServierList = async () => {
  const data = await dictGroup({ dictGroup: 'server_list' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  serverList.value = arry;
}
onMounted(() => {
  loadDataSource();
  getDtaType();
  getServierList();
})
</script>

<style lang="less" scoped></style>
